import java.util.*;

/**
 * @author LKQ
 * @date 2022/5/20 9:55
 * @description 最大堆：维护成本以内的项目利润最大值
 */
public class Solution {
    public static void main(String[] args) {

    }
    public int findMaximizedCapital(int k, int w, int[] profits, int[] capital) {
        int n = profits.length;
        int[][] cp = new int[n][2];
        for (int i = 0; i < n; i++) {
            cp[i][0] = capital[i];
            cp[i][1] = profits[i];
        }
        // 按成本从小到大排序
        Arrays.sort(cp, (a, b) -> a[0] - b[0]);
        // 利润最大堆
        PriorityQueue<Integer> pq = new PriorityQueue<>((x, y) -> y - x);
        int cur = 0;
        for (int i = 0; i < k; i++) {
            while (cur < n && cp[cur][0] <= w) {
                pq.add(cp[cur][1]);
                cur++;
            }
            if (!pq.isEmpty()) {
                w += pq.poll();
            }else {
                break;
            }
        }
        return w;
    }
}
